<?php
/*
	This is the PHP backend file for the AJAX Driven Chat application.
	
	You may use this code in your own projects as long as this copyright is left
	in place.  All code is provided AS-IS.
	This code is distributed in the hope that it will be useful,
 	but WITHOUT ANY WARRANTY; without even the implied warranty of
 	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
	
	For the rest of the code visit http://www.DynamicAJAX.com
	
	Copyright 2005 Ryan Smith / 345 Technical / 345 Group.
*/

//Send some headers to keep the user's browser from caching the response.

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" ); 
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" ); 
header("Cache-Control: no-cache, must-revalidate" ); 
header("Pragma: no-cache" );
header("Content-Type: text/xml; charset=utf-8");

require('../db/database.php');
session_start();

//Check to see if a message was sent.
$result = db_query("SELECT room_id FROM session WHERE session_key = " . $_SESSION['session_key']);
$array = db_fetch_array($result);
$room_id = $array["room_id"];
if(isset($_POST['message']) && $_POST['message'] != '') {

	$result = db_query("SELECT MAX(message_id) as max FROM message");
	$array = db_fetch_array($result);
	$max_id = $array['max'];
	
	if (!is_numeric($max_id)) {
		$max_id = 0;
	} 
	$max_id += 1;
	
	$result = db_query("SELECT username FROM session WHERE session_key = " . $_SESSION['session_key']);
	$row = db_fetch_array($result);
	$sql = "INSERT INTO message(message_id, room_id, username, message, post_time) VALUES (
				$max_id, $room_id, '". $row["username"] ."', '" . db_input($_POST['message']) . "', ".time().")";

	db_query($sql);
}

//Create the XML response.
$xml = '<?xml version="1.0" ?><root>';
$last = (isset($_GET['last']) && $_GET['last'] != '') ? $_GET['last'] : 0;
$sql = "SELECT message_id, username, message, post_time" . 
	" FROM message WHERE room_id = $room_id AND message_id > " . $last;

//print_r ($array);
//echo $sql;
	
//echo "SELECT message_id, username, message, post_time" . 
//	" FROM message WHERE room_id = $room_id AND message_id > " . $last;

$message_query = db_query($sql);
//Loop through each message and create an XML message node for each.
while($message_array = db_fetch_array($message_query)) {
		date_default_timezone_set("Asia/Hong_Kong");
	$xml .= '<message id="' . $message_array['message_id'] . '">';
	$xml .= '<user>' . htmlspecialchars($message_array['username']) . '</user>';
	$xml .= '<text>' . htmlspecialchars($message_array['message']) . '</text>';
	$xml .= '<time>' . date("H:i:s", $message_array['post_time']) . '</time>';
	$xml .= '</message>';
}
$xml .= '</root>';
echo $xml;
?>
